package com.sitr.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;

/**
 * @Description 处理消息的Handler
 * @Author Sitr
 * @Date 2021/3/1 10:17
 * @Version 1.0
 **/


public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    //用于记录和管理所有客户端的CHannel
    private static ChannelGroup clients =
            new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        //客户端传输过来的消息
        String content = textWebSocketFrame.text();
        System.out.println("接收到的消息为" + content);

        for (Channel channel: clients){
            channel.writeAndFlush(new TextWebSocketFrame(
                    "[服务器在]" + LocalDateTime.now()
                            + "接收到消息,消息为" + content));
        }

//        clients.writeAndFlush(new TextWebSocketFrame(
//                "[服务器在]" + LocalDateTime.now()
//                        + "接收到消息,消息为" + content));

    }


    /**
     * @Author Sitr
     * @Description 当客户端连接服务器之后 打开链接
     * 获取客户端的channel 并且放到channel group中
     * @Date 10:23 2021/3/1
     * @Param [ctx]
     * @return void
     **/
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clients.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
//        clients.remove(ctx.channel());//自动移除 不加也可以
        System.err.println("客户端断开channel对应的长ID ： " + ctx.channel().id().asLongText());
        System.err.println("客户端断开channel对应的短ID ： " + ctx.channel().id().asShortText());
    }
}
